package com.leecode.exercise;

/**
 * @Author: shubin_yao
 * @Date: 2022/06/13/12:42
 * @Description:
 */
public class BinaryIndex {

    public static void main(String[] args) {
        int[] nums = {-1, 0, 3, 5, 9, 12};
        Solution solution = new Solution();
        int index = solution.search(nums, 9);
        System.out.println(index);
    }
}


class Solution {

    // nums = [-1,0,3,5,9,12], target = 9
    // 下标：   [0,1,2,3,4,5]
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2 ;
            if (nums[mid] == target) {  //中间
                return mid;
            } else if (nums[mid] < target) {  //右边
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}
